<?php
/**
 * Created by PhpStorm.
 * User: qishengqiang
 * Date: 2022-09-30
 * Time: 12:51
 */

namespace app\services;


use app\models\Configs;
use app\models\WeikeyunOrders;
use app\models\WeikeyunOrdertype;
use GuzzleHttp\Client;

class WeikeyunService extends ServiceBase
{
    protected $config = [];

    protected $weikeyun_url = '';

    protected $weikeyun_token = '';

    protected $order_count = 1000;

    public function __construct()
    {
        $this->config = (new ConfigService())->getAll();
        $this->weikeyun_url = (new ConfigService())->getDetail('weikeyun_url');
        $this->weikeyun_token = (new ConfigService())->getDetail('weikeyun_token');
    }

    /**
     * @throws \Exception
     */
    public function getOrderLists()
    {
        try {
            $url = $this->weikeyun_url.'/api/orders/itemsOrderList';

            $this->getOrderCount();

            $client = new Client();

            $params = [
                'headers' => $this->_get_header(),
                'form_params' => [
                    'page' => 1,
                    'page_size' => $this->order_count,
                    'order_type' => '',
                    //'close_start_time' => date('Y-m-d H:i:s', strtotime('-12 hour')),
                    //'close_end_time' => date('Y-m-d H:i:s'),
                    'status' => 1,
                    'token' => $this->weikeyun_token,
                    'uid' => 6871,
                    'store_id' => 3641
                ]
            ];

            $res = $client->post($url, $params);

            $data = json_decode($res->getBody()->__toString());

            if ($data->code == 200) {
                if (count($data->data->list)) {
                    foreach ($data->data->list as $val) {
                        $order = WeikeyunOrders::where(['wkyOrderId' => $val->id])->find();

                        if (!$order) {
                            $order = new WeikeyunOrders();
                            $order->wkyOrderId = $val->id;
                            $order->picUrl = $val->pic_url;
                            $order->title = $val->title;
                            $order->orderType = $val->order_type;
                            $order->orderNo = $val->orderid;
                            $order->wkyUserId = $val->sub_uid;
                            $order->wkyUserName = $val->username;
                            $order->mobile = $val->mobile;
                            $order->adzoneid = $val->adzoneid;
                            $order->proportion = $val->proportion;
                            $order->amount = $val->amount;
                            $order->tamount = $val->tamount;
                            $order->yamount = $val->yamount;
                            $order->jamount = $val->jamount;
                            $order->orderStatus = $val->status;
                            $order->wkyUpdatedAt = date('Y-m-d H:i:s', $val->update_time);
                        }
                        $order->wkyCreatedAt = $val->create_time;
                        $order->wkyClosedAt = $val->close_time;
                        $order->save();

                        if ($order->status == 0) {
                            $this->addCredit($order);
                        }
                    }
                }
            }
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage(), 500);
        }
    }

    public function addCredit(WeikeyunOrders $order)
    {
        try {
            $url = $this->weikeyun_url.'/api/user/add_user_actionlog';

            $client = new Client();

            $params = [
                'headers' => $this->_get_header(),
                'form_params' => [
                    'type' => 'score',
                    'user_id' => $order->wkyUserId,
                    'num' => bcmul($order->amount, $order->type->proportion, 1),
                    'memo' => $order->type->typeName.'消费积分',
                    'token' => $this->weikeyun_token,
                    'uid' => 6871,
                    'store_id' => 3641
                ]
            ];

            $res = $client->post($url, $params);

            $data = json_decode($res->getBody()->__toString());

            $order->status = $data->code;
            $order->save();

        } catch (\Exception $e) {
            throw new \Exception($e->getMessage(), 500);
        }
    }

    public function getAccessToken()
    {
        try {
            $url = $this->weikeyun_url.'/api/Log/login';

            $client = new Client();

            $params = [
                'headers' => $this->_get_header(),
                'form_params' => [
                    'mobile' => $this->config['weikeyun_account'],
                    'password' => $this->config['weikeyun_password'],
                    'loginType' => 0
                ]
            ];

            $res = $client->post($url, $params);

            $data = json_decode($res->getBody()->__toString());

            if ($data->code == 1) {
                $array = [
                    [
                        'configKey' => 'weikeyun_token',
                        'configValue' => $data->data->token
                    ]
                ];
                (new ConfigService())->update($array);
            }
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage(), 500);
        }
    }

    private function _get_header()
    {
        $headers = [
            "Accept" => "application/json, text/plain, */*",
            "Accept-Encoding" => "gzip, deflate, br",
            "Accept-Language" => "zh-CN,zh;q=0.9,en;q=0.8",
            "Access-Token" => $this->weikeyun_token,
            "Connection" => "keep-alive",
            "Content-Type" => "application/x-www-form-urlencoded; charset=UTF-8",
            "Cookie" => "PHPSESSID=10f74ea2c464b017fa6d81dded169422",
            "Host" => "control.wikeyun.cn",
            "Origin" => "https://control.wikeyun.cn",
            "sec-ch-ua" => '"Google Chrome";v="105", "Not)A;Brand";v="8", "Chromium";v="105"',
            "sec-ch-ua-mobile" => "?0",
            "sec-ch-ua-platform" => '"macOS"',
            "Sec-Fetch-Dest" => "empty",
            "Sec-Fetch-Mode" => "cors",
            "Sec-Fetch-Site" => "same-origin",
            "User-Agent" => "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36"
        ];

        return $headers;
    }

    public function getOrderCount()
    {
        $url = $this->weikeyun_url.'/api/orders/itemsOrderList';

        $client = new Client();

        $params = [
            'headers' => $this->_get_header(),
            'form_params' => [
                'page' => 1,
                'page_size' => 10,
                'order_type' => '',
                'status' => 1,
                'token' => $this->weikeyun_token,
                'uid' => 6871,
                'store_id' => 3641
            ]
        ];

        $res = $client->post($url, $params);

        $data = json_decode($res->getBody()->__toString());

        if ($data->code == 200) {
            $this->order_count = $data->data->count;
        }
    }
}